import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { LoginForm, LoginRequest } from '../types'

/**
 * 登录页面状态管理
 */
export function useLoginPageState() {
  const router = useRouter()

  // 加载状态
  const isLoading = ref(false)

  // 表单数据
  const loginForm = reactive<LoginForm>({
    username: '',
    password: '',
    rememberMe: false
  })

  /**
   * 重置表单
   */
  const resetForm = (): void => {
    loginForm.username = ''
    loginForm.password = ''
    loginForm.rememberMe = false
  }

  /**
   * 验证表单数据
   */
  const validateForm = (): boolean => {
    if (!loginForm.username.trim()) {
      ElMessage.warning('请输入用户名')
      return false
    }

    if (!loginForm.password.trim()) {
      ElMessage.warning('请输入密码')
      return false
    }

    if (loginForm.username.length < 3 || loginForm.username.length > 20) {
      ElMessage.warning('用户名长度在 3 到 20 个字符')
      return false
    }

    if (loginForm.password.length < 6 || loginForm.password.length > 20) {
      ElMessage.warning('密码长度在 6 到 20 个字符')
      return false
    }

    return true
  }

  /**
   * 执行登录
   */
  const performLogin = async (loginData: LoginRequest): Promise<void> => {
    try {
      isLoading.value = true

      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1500))

      // 这里应该调用实际的登录API
      console.log('登录请求:', loginData)

      // 模拟登录成功
      ElMessage.success('登录成功！')

      // 存储用户信息到本地存储
      if (loginData.rememberMe) {
        localStorage.setItem('rememberMe', 'true')
        localStorage.setItem('username', loginData.username)
      } else {
        localStorage.removeItem('rememberMe')
        localStorage.removeItem('username')
      }

      // 跳转到仪表板
      await router.push('/dashboard')

    } catch (error) {
      console.error('登录失败:', error)
      ElMessage.error('登录失败，请检查用户名和密码')
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 初始化表单数据（从本地存储恢复）
   */
  const initializeForm = (): void => {
    const rememberMe = localStorage.getItem('rememberMe') === 'true'
    const savedUsername = localStorage.getItem('username')

    if (rememberMe && savedUsername) {
      loginForm.username = savedUsername
      loginForm.rememberMe = true
    }
  }

  return {
    isLoading,
    loginForm,
    resetForm,
    validateForm,
    performLogin,
    initializeForm
  }
}
